#!/usr/bin/env python
"""Flask 应用管理脚本"""
import os
import click
from flask.cli import with_appcontext
from flask import current_app
from app import create_app
from app.extensions import db
from app.models import User


@click.group()
def cli():
    """Flask 应用管理命令"""
    pass


@cli.command()
@with_appcontext
def init_db():
    """初始化数据库"""
    db.create_all()
    click.echo("数据库初始化完成!")


@cli.command()
@with_appcontext
def drop_db():
    """删除数据库"""
    if click.confirm('确定要删除所有数据吗？'):
        db.drop_all()
        click.echo("数据库已删除!")


@cli.command()
@click.option('--username', prompt='用户名', help='管理员用户名')
@click.option('--email', prompt='邮箱', help='管理员邮箱')
@click.option('--password', prompt='密码', hide_input=True, help='管理员密码')
@with_appcontext
def create_admin(username, email, password):
    """创建管理员用户"""
    # 检查用户名是否已存在
    if User.query.filter_by(username=username).first():
        click.echo(f"用户名 '{username}' 已存在!")
        return
    
    # 检查邮箱是否已存在
    if User.query.filter_by(email=email).first():
        click.echo(f"邮箱 '{email}' 已被注册!")
        return
    
    # 创建管理员用户
    admin = User(
        username=username,
        email=email,
        is_admin=True,
        is_active=True
    )
    admin.password = password
    
    db.session.add(admin)
    db.session.commit()
    
    click.echo(f"管理员用户 '{username}' 创建成功!")


@cli.command()
@click.option('--count', default=10, help='创建的测试用户数量')
@with_appcontext
def create_test_users(count):
    """创建测试用户"""
    for i in range(count):
        username = f"testuser{i+1}"
        email = f"testuser{i+1}@example.com"
        
        # 检查用户是否已存在
        if User.query.filter_by(username=username).first():
            continue
        
        user = User(
            username=username,
            email=email,
            first_name=f"Test{i+1}",
            last_name="User",
            is_active=True
        )
        user.password = "password123"
        
        db.session.add(user)
    
    db.session.commit()
    click.echo(f"创建了 {count} 个测试用户!")


@cli.command()
@with_appcontext
def list_users():
    """列出所有用户"""
    users = User.query.all()
    
    click.echo("用户列表:")
    click.echo("-" * 80)
    click.echo(f"{'ID':<5} {'用户名':<15} {'邮箱':<25} {'管理员':<8} {'激活':<8}")
    click.echo("-" * 80)
    
    for user in users:
        click.echo(f"{user.id:<5} {user.username:<15} {user.email:<25} "
                  f"{'是' if user.is_admin else '否':<8} {'是' if user.is_active else '否':<8}")


@cli.command()
@with_appcontext
def compile_translations():
    """编译翻译文件"""
    import subprocess
    try:
        result = subprocess.run(['pybabel', 'compile', '-d', 'app/translations'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            click.echo("翻译文件编译成功!")
        else:
            click.echo(f"编译失败: {result.stderr}")
    except FileNotFoundError:
        click.echo("错误: 请先安装 babel")


@cli.command()
@with_appcontext
def extract_translations():
    """提取翻译字符串"""
    import subprocess
    try:
        result = subprocess.run([
            'pybabel', 'extract', '-F', 'babel.cfg', '-k', '_', '-o', 'messages.pot', '.'
        ], capture_output=True, text=True)
        if result.returncode == 0:
            click.echo("翻译字符串提取成功!")
        else:
            click.echo(f"提取失败: {result.stderr}")
    except FileNotFoundError:
        click.echo("错误: 请先安装 babel")


@cli.command()
@with_appcontext
def run_tests():
    """运行测试"""
    import subprocess
    try:
        result = subprocess.run(['pytest', '-v'], capture_output=True, text=True)
        click.echo(result.stdout)
        if result.stderr:
            click.echo(result.stderr)
    except FileNotFoundError:
        click.echo("错误: 请先安装 pytest")


if __name__ == '__main__':
    # 创建应用上下文
    app = create_app()
    with app.app_context():
        cli() 